/**
 * Created by lenovo on 2017/7/20.
 */
let DBPool = require('../dao/DBConnectPool');
let WXMember = require('./WXMemberController');
let request = require('request');

module.exports = {
    showFootprint:function (req, res) {
        let title = '足迹';
        WXMember.checkPhoneNumber(req,res,function (err, code, result) {
            if (code){
                if(code == 10001){
                    res.render('wx-activation', {
                        title: '手机号绑定',
                    });
                } else {
                    res.render('wx-404', {
                        title: title,
                        errorMessage: err
                    });
                }
            } else {
                res.render('wx-footprint',{
                    title:title
                })
            }
        });
    },
    getFootprint:function (req, res) {
        let type = req.body.type;
        let lastIndexCinema = req.body.lastIndexCinema;
        let lastIndexMovie = req.body.lastIndexMovie;
        let lat = req.body.lat;
        let lng = req.body.lng;

        if ( req.signedCookies.userinfo && req.signedCookies.userinfo.openid ){
            let url = 'http://bizserver.bestmovie.com.cn:3000/wechat/'
            //let openid = 'oSx2ps2IxQrINLDI4KvwcPoeuxr0';
            let openid = req.signedCookies.userinfo.openid;
            if (type == 0){
                let formData = {
                    openId:openid,
                    lastIndex: parseInt(lastIndexMovie),
                };
                request({
                    headers:{
                        'Content-Type':'application/json'
                    },
                    url: url+'playfootmovie',
                    method:'post',
                    body: JSON.stringify(formData)

                },function (err, response, body) {
                    console.log('WXFootprintController.js--->'+body);
                    try {
                        let responseJson = JSON.parse(body);
                        if (responseJson['status'] == 'fail') {
                            res.json({errorMessage: '获取影片足迹失败！'});
                        } else {
                            if (responseJson['data'].length > 0){
                                DBPool.getPoolConnection('mtsc', function (err, connection) {
                                    if (err) {
                                        res.json({errorMessage: '数据库链接错误'});
                                        connection.release();
                                        return;
                                    }
                                    let mArray = [];
                                    let sql = 'SELECT *,DATE_FORMAT(publishdate,"%Y-%m-%d") as publish ' +
                                        ' FROM movie ' +
                                        ' WHERE mid = ? ' +
                                        ' ORDER BY publishdate DESC ';
                                    for (let i=0;i<responseJson['data'].length;i++){
                                        connection.query(sql,[responseJson['data'][i].mid] ,function (queryErr, rows) {
                                            if (queryErr) {
                                                res.json({errorMessage: '获取影片足迹失败！'});
                                                connection.release();
                                            } else {
                                                if(rows.length > 0) {
                                                    responseJson['data'][i].poster = rows[0].poster;
                                                    responseJson['data'][i].movie_name = rows[0].movie_name;
                                                    responseJson['data'][i].score = rows[0].score;
                                                    responseJson['data'][i].category = rows[0].category;
                                                    responseJson['data'][i].publish = rows[0].publish;

                                                    mArray.push(responseJson['data'][i]);
                                                }

                                                if (i === responseJson['data'].length - 1) {
                                                    res.json(mArray);
                                                    connection.release();
                                                }
                                            }
                                        })
                                    }
                                });
                            } else {
                                res.json(responseJson['data']);
                            }
                        }
                    } catch (error) {
                        res.json({errorMessage: error});
                    }
                });
            } else if (type == 1){
                let formData = {
                    openId:openid,
                    lastIndex: parseInt(lastIndexCinema),
                };
                request({
                    headers:{
                        'Content-Type':'application/json'
                    },
                    url: url+'playfootcinema',
                    method:'post',
                    body: JSON.stringify(formData)

                },function (err, response, body) {
                    console.log('WXFootprintController.js--->'+body);
                    try {
                        let responseJson = JSON.parse(body);
                        if (responseJson['status'] == 'fail') {
                            res.json({errorMessage: '获取点播影院足迹失败！'});
                        }else {
                            if (responseJson['data'].length > 0){
                                DBPool.getPoolConnection('mtsc', function (err, connection) {
                                    if (err) {
                                        res.json({errorMessage: '数据库链接错误'});
                                        connection.release();
                                        return;
                                    }
                                    let mArray = [];
                                    let sql = 'SELECT c.* ,b.name as region_name , ' +
                                        ' (c.cinema_lat - ?) * (c.cinema_lat - ?) + (c.`cinema_long` - ?) * (c.`cinema_long` - ?) AS distance ' +
                                        ' FROM cinema as c' +
                                        ' INNER JOIN cinema_region AS b ON c.cinema_regionid = b.id' +
                                        ' WHERE c.cinema_code = ? ';
                                    for (let i=0;i<responseJson['data'].length;i++){
                                        connection.query(sql,[lat,lat,lng,lng,responseJson['data'][i].cid] ,function (queryErr, rows) {

                                            if (queryErr) {
                                                console.log('WXFootprintController.js'+queryErr);
                                                res.json({errorMessage: '获取点播影院足迹失败！'});
                                                connection.release();
                                            } else {
                                                if(rows.length > 0) {
                                                    responseJson['data'][i].cinema_code = rows[0].cinema_code;
                                                    responseJson['data'][i].cinema_picture = rows[0].cinema_picture;
                                                    responseJson['data'][i].cinema_name = rows[0].cinema_name;
                                                    responseJson['data'][i].tag_1 = rows[0].tag_1;
                                                    responseJson['data'][i].tag_2 = rows[0].tag_2;
                                                    responseJson['data'][i].tag_3 = rows[0].tag_3;
                                                    responseJson['data'][i].tag_4 = rows[0].tag_4;
                                                    responseJson['data'][i].tag_5 = rows[0].tag_5;
                                                    responseJson['data'][i].tag_6 = rows[0].tag_6;
                                                    responseJson['data'][i].tag_7 = rows[0].tag_7;
                                                    responseJson['data'][i].tag_8 = rows[0].tag_8;
                                                    responseJson['data'][i].score = rows[0].score;
                                                    responseJson['data'][i].price = rows[0].price;
                                                    responseJson['data'][i].region_name = rows[0].region_name;
                                                    responseJson['data'][i].distance = rows[0].distance;

                                                    mArray.push(responseJson['data'][i]);
                                                }

                                                if (i === responseJson['data'].length - 1) {
                                                    res.json(mArray);
                                                    connection.release();
                                                }
                                            }
                                        })
                                    }
                                });
                            } else {
                                res.json(responseJson['data']);
                            }
                        }
                    } catch (error){
                        res.json({errorMessage: error});
                    }
                });
            } else {
                res.json({errorMessage: '参数错误！'});
            }

        } else {
            res.json({errorMessage: 'openid取得失败！'});
        }

        // WXMember.checkPhoneNumber(req,res,function (err, code, result) {
        //     if (code){
        //         res.json({errorMessage: err});
        //     } else {
        //
        //
        //         DBPool.getPoolConnection('mtsc', function (err, connection) {
        //             if (err) {
        //                 res.json({errorMessage: '数据库链接错误'});
        //                 connection.release();
        //                 return;
        //             }
        //             let sql = '';
        //             let page = 0;
        //
        //             if (type == 0){
        //                 sql = 'SELECT m.*,DATE_FORMAT(m.publishdate,"%Y-%m-%d") as publish ' +
        //                     ' FROM member_movie_footprint AS c ' +
        //                     ' INNER JOIN movie as m ON m.mid = c.mid ' +
        //                     ' WHERE c.member_id = ? ' +
        //                     ' ORDER BY c.updatetime DESC ' +
        //                     ' LIMIT ?,? ';
        //                 page = pageMovie*limit;
        //             } else if (type == 1){
        //                 sql = 'SELECT m.* ' +
        //                     ' FROM member_cinema_footprint AS c ' +
        //                     ' INNER JOIN cinema as m ON c.cinema_code = m.cinema_code ' +
        //                     ' WHERE c.member_id = ? ' +
        //                     ' ORDER BY c.updatetime DESC ' +
        //                     ' LIMIT ?,? ';
        //                 page = pageCinema*limit;
        //             } else {
        //                 res.json({errorMessage: '参数错误！'});
        //                 connection.release();
        //                 return;
        //             }
        //
        //             connection.query(sql,[result.member_id,page,limit] ,function (queryErr, rows) {
        //                 if (queryErr) {
        //                     res.json({errorMessage: '获取收藏信息失败！'});
        //                 } else {
        //                     let flg = 0;
        //                     if (rows.length < limit) {
        //                         flg = 1;
        //                     }
        //                     res.json({
        //                         footprint: rows,
        //                         isLast:flg
        //                     });
        //                 }
        //                 connection.release();
        //             })
        //         });
        //     }
        // });
    }
};
